package com.dgut.lotterySystem.controller;

import com.dgut.lotterySystem.common.pojo.CommonResult;
import com.dgut.lotterySystem.common.utils.JacksonUtil;
import com.dgut.lotterySystem.controller.param.DrawPrizeParam;
import com.dgut.lotterySystem.controller.param.ShowWinningRecordsParam;
import com.dgut.lotterySystem.controller.result.ShowWinningRecordsResult;
import com.dgut.lotterySystem.service.dto.ShowWinningRecordsDTO;
import com.dgut.lotterySystem.service.impl.DrawPrizeServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/draw")
public class DrawPrizeController {

    private static final Logger logger= LoggerFactory.getLogger(DrawPrizeController.class);

    @Autowired
    private DrawPrizeServiceImpl drawPrizeService;
    @PostMapping("/drawPrize")
    public CommonResult<Boolean> drawPrize(@RequestBody DrawPrizeParam param){
        logger.info("drawPrize DrawPrizeParam {}",JacksonUtil.writeValueAsString(param));
        drawPrizeService.drawPrize(param);
        return CommonResult.success(Boolean.TRUE);
    }

    @PostMapping("/getWinningRecords")
    public CommonResult<List<ShowWinningRecordsResult>> ShowWinningRecords(
            @Validated @RequestBody ShowWinningRecordsParam param ){
        logger.info("ShowWinningRecords ShowWinningRecordsParam:{}", JacksonUtil.writeValueAsString(param));

        List<ShowWinningRecordsDTO> winningRecordsDTOList=drawPrizeService.ShowWinningRecords(param);
        return CommonResult.success(convertShowWinningRecordsResult(winningRecordsDTOList));
    }

    private List<ShowWinningRecordsResult> convertShowWinningRecordsResult(
            List<ShowWinningRecordsDTO> winningRecordsDTOList) {
        if(CollectionUtils.isEmpty(winningRecordsDTOList)){
            return Arrays.asList();
        }
        List<ShowWinningRecordsResult> result=winningRecordsDTOList.stream().map(showWinningRecordsDTO->{
            ShowWinningRecordsResult showWinningRecord=new ShowWinningRecordsResult();
            showWinningRecord.setWinningId(showWinningRecordsDTO.getWinningId());
            showWinningRecord.setWinnerName(showWinningRecordsDTO.getWinnerName());
            showWinningRecord.setPrizeName(showWinningRecordsDTO.getPrizeName());
            showWinningRecord.setPrizeTier(showWinningRecordsDTO.getPrizeTier().getMessage());
            showWinningRecord.setWinningTime(showWinningRecordsDTO.getWinningTime());
            return showWinningRecord;
        }).collect(Collectors.toList());
        return result;
    }
}
